﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OAuth2.Provider.IService;
using OAuth2.Repository;
using OAuth2.Framework;
using OAuth2.Repository.Model;

namespace OAuth2.Provider.Service
{
    public class ClientService:IClientService
    {
        readonly IClientRepository ClientRepo;
        readonly ITokenRepository TokenRepo;

        public ClientService(IClientRepository repo,ITokenRepository  tokenRepo) 
        {
            ClientRepo = repo;
            TokenRepo  = tokenRepo;
        }

        #region IClientService 成员

        public bool AuthenticateClient(IOAuthContext context)
        {
            Client actual = ClientRepo.FindClient(context.Client.ClientID);
            if (actual == null) return false;

            return actual.ClientSecret == context.Client.ClientSecret;
        }

        public bool ValidDateRedirectUri(IOAuthContext context)
        {
            Client cl = ClientRepo.FindClient(context.Client.ClientID);
            return context.Client.RedirectUri.Equals(cl.RedirectUri);
        }

        public bool IsClient(IOAuthContext context)
        {
            return ClientRepo.FindClient(context.Client.ClientID) != null;
        }

        public IClient FindClient(string clientID)
        {
            return ClientRepo.FindClient(clientID);
        }

        public bool IsAccessGranted(IClient client, string[] scope, string resourceOwnerID)
        {
            AuthorizationGrant grant = TokenRepo.FindAuthorizationGrant(client.ClientID, resourceOwnerID);
            if (grant == null) return false;
            if (!grant.IsApproved) return false;
            return true;
        }

        #endregion

    }
}
